import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/api_path.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/dialog/share_bottom_sheet.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/home/model/user_info_entity.dart';
import 'package:tender_flutter/providers/provider.dart';
import 'package:tender_flutter/providers/user_profile.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/share.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/net_image.dart';

import 'api/api_person.dart';

class TabPersonPage extends StatefulWidget {
  @override
  _TabPersonPageState createState() => _TabPersonPageState();
}

class _TabPersonPageState extends State<TabPersonPage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  /// 获取用户信息
  Future _getUserInfo() async {
    var response = await ApiPerson.getUserInfo<UserInfoEntity>();
    Store.value<UserProfileInfo>(context).setUserInfo(response.result);
    if (_refreshController.isRefresh) {
      _refreshController.refreshCompleted();
    }
  }

  @override
  bool get wantKeepAlive => false;

  @override
  void initState() {
    super.initState();

    /// 页面渲染完成之后的回调，只执行一次
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      _getUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("执行了PersonPage-->Build");
    return Scaffold(
      body: Stack(children: [_initBody(), _initAppBar()]),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return Container(
        height: ScreenAdapter.statusBarHeight() + kToolbarHeight,
        child: BaseAppBar(
          context,
          Text("个人中心",
              style: FonStyle.navTextStyle(textColor: ThemeColors.colorWhite)),
          backgroundColor: Colors.transparent,
          isShowLeading: false,
          brightness: Brightness.dark,
          elevation: 0,
        ));
  }

  /// 内容
  Widget _initBody() {
    return SmartRefresher(
        physics: BouncingScrollPhysics(),
        controller: _refreshController,
        enablePullUp: false,
        enablePullDown: true,
        onRefresh: _getUserInfo,
        child: SingleChildScrollView(
            child: Column(
          children: <Widget>[
            _initUserInfoView(),
            _initBaseInfoList(),
            _initAdvert(),
            _initOtherList()
          ],
        )));
  }

  /// 用户信息
  Widget _initUserInfoView() {
    return Container(
      // height: ScreenAdapter.height(420),
      // height: ScreenAdapter.height(330),
      height: ScreenAdapter.height(420),
      width: double.infinity,
      color: ThemeColors.colorWhite,
      child: Consumer(builder:
          (BuildContext ctx, UserProfileInfo profileInfo, Widget child) {
        return Stack(
          fit: StackFit.expand,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: ScreenAdapter.height(65)),
              child: Image.asset(
                RPath.imgPath + "img_person_top_bg.png",
                fit: BoxFit.fill,
              ),
            ),
            Positioned(
                // bottom: ScreenAdapter.height(80),
                bottom: ScreenAdapter.height(170),
                child: Container(
                  width: ScreenAdapter.screenWidth(),
                  margin: EdgeInsets.only(left: ScreenAdapter.width(32)),
                  child: Row(
                    children: <Widget>[
                      Container(
                          width: ScreenAdapter.width(110),
                          height: ScreenAdapter.width(110),
                          decoration: BoxDecoration(
                            border: new Border.all(
                              color: ThemeColors.colorWhite, //边框颜色
                              width: 1, //边框宽度
                            ),
                            borderRadius:
                                BorderRadius.circular(ScreenAdapter.width(55)),
                          ),
                          child: MyNetImage(
                              url: profileInfo.userInfo != null
                                  ? profileInfo.userInfo.picture ?? ""
                                  : "",
                              radius: BorderRadius.circular(
                                  ScreenAdapter.width(52)),
                              placeholder: Image.asset(RPath.imgPath +
                                  "img_portait_placeholder.png"),
                              imageClickAction: (state) {
                                LRouter.navigatorCtx(context)
                                    .push(Routes.personInfoPage);
                              })),
                      SizedBox(width: ScreenAdapter.width(20)),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(profileInfo.userInfo.phone ?? "-",
                              style: TextStyle(
                                fontSize: ScreenAdapter.sp(33),
                                color: ThemeColors.colorWhite,
                                fontWeight: FontWeight.bold,
                              )),
                          SizedBox(height: ScreenAdapter.height(15)),
                          Text(_getMyVipDes(entity: profileInfo.userInfo),
                              maxLines: 1,
                              style: TextStyle(
                                fontSize: ScreenAdapter.sp(23),
                                color: ThemeColors.colorType22,
                              )),
                        ],
                      ),
                      Expanded(child: SizedBox()),
                      Align(
                          alignment: Alignment.centerLeft,
                          child: Offstage(
                              offstage: DataManager.instance.isAppstore
                                  ? true
                                  : false,
                              child: Container(
                                // width: ScreenAdapter.width(160),
                                height: ScreenAdapter.height(60),
                                decoration: BoxDecoration(
                                  image: DecorationImage(
                                      image: AssetImage(
                                          RPath.imgPath + "img_vip_btn_bg.png"),
                                      fit: BoxFit.fill),
                                ),
                                alignment: Alignment.center,
                                child: FlatButton(
                                  onPressed: () {
                                    LRouter.navigatorCtx(context)
                                        .push(Routes.memberCentrePage);
                                  },
                                  child: Text(
                                    profileInfo.userInfo.isVip()
                                        ? "续费"
                                        : "开通会员",
                                    maxLines: 1,
                                    style: TextStyle(
                                        color: ThemeColors.colorWhite,
                                        fontSize: ScreenAdapter.sp(24)),
                                  ),
                                  color: Colors.transparent,
                                ),
                              )))
                    ],
                  ),
                )),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                margin: EdgeInsets.only(
                    left: ScreenAdapter.width(32),
                    right: ScreenAdapter.width(32),
                    bottom: ScreenAdapter.height(15)),
                padding: EdgeInsets.symmetric(
                    horizontal: ScreenAdapter.width(25),
                    vertical: ScreenAdapter.height(15)),
                height: ScreenAdapter.height(130),
                width: double.infinity,
                decoration: BoxDecoration(
                  color: ThemeColors.colorWhite,
                  borderRadius:
                      new BorderRadius.circular(ScreenAdapter.width(20)),
                  boxShadow: [
                    BoxShadow(
                      blurRadius: 10, //阴影范围
                      spreadRadius: 1, //阴影浓度
                      color: ThemeColors.colorType21, //阴影颜色
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text("我的收益",
                            style: TextStyle(
                              fontSize: ScreenAdapter.sp(24),
                              color: ThemeColors.colorType7,
                            )),
                        profileInfo.userInfo.money == 0.0
                            ? Text("暂无收益！赶紧分享给朋友吧！",
                                style: TextStyle(
                                    fontSize: ScreenAdapter.sp(23),
                                    color: ThemeColors.colorType14))
                            : RichText(
                                text: TextSpan(
                                text: '¥ ',
                                style: TextStyle(
                                    fontSize: ScreenAdapter.sp(28),
                                    color: ThemeColors.colorType63,
                                    fontWeight: FontWeight.bold),
                                children: <TextSpan>[
                                  TextSpan(
                                    text: "${profileInfo.userInfo.money}",
                                    style: TextStyle(
                                        fontSize: ScreenAdapter.sp(40),
                                        color: ThemeColors.colorType63,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ],
                              ))
                      ],
                    ),
                    SizedBox(
                      width: ScreenAdapter.width(140),
                      height: ScreenAdapter.height(60),
                      child: FlatButton(
                        color: ThemeColors.colorType12,
                        shape: RoundedRectangleBorder(
                          borderRadius:
                              BorderRadius.circular(ScreenAdapter.height(30)),
                        ),
                        child: Text(
                          profileInfo.userInfo.money == 0.0 ? "分享" : "提现",
                          style: TextStyle(
                              color: ThemeColors.colorWhite,
                              fontSize: ScreenAdapter.sp(28)),
                        ),
                        onPressed: () {
                          if (profileInfo.userInfo.money == 0.0) {
                            LRouter.navigatorCtx(context)
                                .push(Routes.inviatePage);
                          } else {
                            LRouter.navigatorCtx(context)
                                .push(Routes.tiXianHistoryPage);
                          }
                        },
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        );
      }),
    );
  }

  String _getMyVipDes({UserInfoEntity entity}) {
    if (DataManager.instance.isAppstore) {
      return "您的鼓励是我们的最大动力";
    }
    if (entity.level > 0 && !entity.vipValid) {
      // 代表用户购买的次数已用完
      return "您的会员已过期，续费可继续查看";
    } else if (entity.level > 0 && entity.vipValid) {
      // 代表用户是有效会员
      return "您的会员${entity.expireDate}到期";
    }
    return "开通会员尊享更多特权";
  }

  /// 广告
  Widget _initAdvert() {
    return Offstage(
        offstage: DataManager.instance.isAppstore ? true : false,
        child: GestureDetector(
            onTap: () {
              LRouter.navigatorCtx(context).push(Routes.memberCentrePage);
            },
            child: Container(
                // color: Colors.indigoAccent,
                height: ScreenAdapter.height(180),
                width: double.infinity,
                child: Image.asset(
                  RPath.imgPath + "img_person_adv.png",
                  fit: BoxFit.cover,
                ))));
  }

  /// 条目
  Widget _initBaseInfoList() {
    return Container(
        height: ScreenAdapter.height(140),
        // color: Colors.red,
        child: Consumer(builder:
            (BuildContext ctx, UserProfileInfo profileInfo, Widget child) {
          return ListView(
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            children: <Widget>[
              _getVerticalItem("基本信息", "icon_person_my_demand.png", () {
                LRouter.navigatorCtx(context).push(Routes.personInfoPage);
              }),
              _getVerticalItem("我的消息", "icon_person_news.png", () {
                LRouter.navigatorCtx(context).push(Routes.newsPage);
              },
                  showBadge:
                      profileInfo.userInfo.msgUnreadNum != 0 ? true : false),
              _getVerticalItem("我的供需", "icon_person_info.png", () {
                LRouter.navigatorCtx(context).push(Routes.personMarketPage);
              }),
              _getVerticalItem("我的收藏", "icon_person_collect.png", () {
                LRouter.navigatorCtx(context).push(Routes.personCollectionPage);
              }),
            ],
          );
        }));
  }

  /// 条目
  Widget _initOtherList() {
    return ListView(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(vertical: ScreenAdapter.height(15)),
      scrollDirection: Axis.vertical,
      children: <Widget>[
        _getHorizontalItem("购买记录", "icon_person_buy_record.png", () {
          LRouter.navigatorCtx(context).push(Routes.consumptionPage);
        }),
        _getHorizontalItem("分享返佣", "icon_person_share.png", () {
          LRouter.navigatorCtx(context).push(Routes.inviatePage);
        }),
        _getHorizontalItem("关于我们", "icon_person_about.png", () {
          LRouter.navigatorCtx(context).push(Routes.aboutPage);
        }),
        _getHorizontalItem("意见反馈", "icon_personal_custom.png", () {
          LRouter.navigatorCtx(context).push(Routes.feedbackPage);
        }),
        _getHorizontalItem("设置", "icon_person_setting.png", () {
          LRouter.navigatorCtx(context).push(Routes.settingPage);
        }),
      ],
    );
  }

  /// 垂直排列Item
  Widget _getVerticalItem(
      String text, String image, GestureTapCallback callback,
      {bool showBadge = false}) {
    return InkWell(
      child: Container(
        // color: Colors.green,
        width: ScreenAdapter.screenWidth() / 4,
        height: ScreenAdapter.screenWidth() / 4,
        alignment: Alignment.center,
        // padding: EdgeInsets.only(
        //   top: ScreenAdapter.height(20),
        //   // bottom: ScreenAdapter.height(20),
        // ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Badge(
                showBadge: showBadge,
                child: Image.asset(
                  RPath.imgPath + "$image",
                  width: ScreenAdapter.width(46),
                  height: ScreenAdapter.width(46),
                )),
            SizedBox(height: ScreenAdapter.height(15)),
            Text(text,
                style: TextStyle(
                    color: ThemeColors.colorType23,
                    fontSize: ScreenAdapter.sp(30)))
          ],
        ),
      ),
      onTap: callback,
    );
  }

  /// 水平排列Item
  Widget _getHorizontalItem(
      String text, String image, GestureTapCallback callback) {
    return Column(children: [
      InkWell(
        child: Container(
          width: double.infinity,
          height: ScreenAdapter.height(60),
          padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
          child: Row(
            children: <Widget>[
              Image.asset(RPath.imgPath + "$image",
                  fit: BoxFit.fitHeight,
                  width: ScreenAdapter.width(30),
                  height: ScreenAdapter.width(30)),
              SizedBox(width: ScreenAdapter.width(15)),
              Text(text,
                  style: TextStyle(
                      color: ThemeColors.colorType24,
                      fontSize: ScreenAdapter.sp(30))),
              Expanded(child: SizedBox()),
              Image.asset(
                RPath.imgPath + "icon_person_right_arrow.png",
                width: ScreenAdapter.width(12),
                height: ScreenAdapter.height(23),
              ),
            ],
          ),
        ),
        onTap: callback,
      ),
      Divider(color: ThemeColors.colorType45)
    ]);
  }
}
